<?php

namespace yi\base;

use Yi;

class Controller extends Component implements ViewContextInterface
{
    public $controllerNamespace;
    public $defaultRoute = 'default';
    public $_viewPath;
    public $id;
    /**
     * @var Module $module
     */
    public $module;

    public function __construct($id, $module, $config = [])
    {
        $this->id = $id;
        $this->module = $module;
        parent::__construct($config);
    }

    /**
     * @var View|null the view object that can be used to render views or view files.
     */
    private $_view;

    public function runAction($actionID, $params)
    {
        $methodName = 'action' . str_replace(' ', '', ucwords(str_replace('-', ' ', $actionID)));
        return call_user_func_array([$this, $methodName], $params);
    }


    public function render($view, $params = [])
    {
        $content = $this->getView()->render($view, $params, $this);
        return $this->renderContent($content);
    }

    /**
     * Renders a static string by applying a layout.
     * @param string $content the static string being rendered
     * @return string the rendering result of the layout with the given static string as the `$content` variable.
     * If the layout is disabled, the string will be returned back.
     * @since 2.0.1
     */
    public function renderContent($content)
    {
        $layoutFile = $this->findLayoutFile($this->getView());
        if ($layoutFile !== false) {
            return $this->getView()->renderFile($layoutFile, ['content' => $content], $this);
        }

        return $content;
    }


    public function getView()
    {
        if ($this->_view === null) {
            $this->_view = Yi::$app->getView();
        }

        return $this->_view;
    }

    public function getViewPath()
    {
        if ($this->_viewPath === null) {
            $this->_viewPath = $this->module->getViewPath() . DIRECTORY_SEPARATOR . $this->id;
        }

        return $this->_viewPath;
    }
}